<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\DateFormat;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 学期设置
 *
 * @icon fa fa-circle-o
 */
class Semester extends Backend
{

    /**
     * Semester模型对象
     * @var \app\common\model\Semester
     */
    protected $model = null;
    protected $noNeedRight = ['select', 'selectWeekList'];
    protected $schoolLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Semester;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['school'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['school'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {

                $row->getRelation('school')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $daterange = $this->request->request('daterange');
                list($params['start_date'], $params['end_date']) = explode(' - ', $daterange);

                $count = $this->model->where('school_id', $params['school_id'])
                    ->where(function ($query) use ($params) {
                        $query ->where(function ($q) use ($params) {
                            $q->where('start_date', '>=', $params['start_date'])->where('start_date', '<=', $params['end_date']);
                        })
                        ->whereOr(function ($q) use ($params) {
                            $q->where('end_date', '>=', $params['start_date'])->where('end_date', '<=', $params['end_date']);
                        });
                    })
                    ->count();

                if ($count) {
                    $this->error('日期不能与其他学期重合');
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $daterange = $this->request->request('daterange');
                list($params['start_date'], $params['end_date']) = explode(' - ', $daterange);

                $count = $this->model->where('school_id', $params['school_id'])
                    ->where('id', '<>', $row->id)
                    ->where(function ($query) use ($params) {
                        $query ->where(function ($q) use ($params) {
                            $q->where('start_date', '>=', $params['start_date'])->where('start_date', '<=', $params['end_date']);
                        })
                            ->whereOr(function ($q) use ($params) {
                                $q->where('end_date', '>=', $params['start_date'])->where('end_date', '<=', $params['end_date']);
                            });
                    })
                    ->count();

                if ($count) {
                    $this->error('日期不能与其他学期重合');
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $schoolIds = $this->getDataLimitSchoolIds();
            if (is_array($schoolIds)) {
                $this->model->where($this->schoolLimitField, 'in', $schoolIds);
            }

            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function select()
    {
        $school_id = $this->request->request('school_id');
        $list = $this->model->where('school_id', $school_id)
            ->where('end_date', '>', date('Y-m-d', time()))
            ->select();
        $this->success('', null, $list);
    }

    public function selectWeekList()
    {
        $id = $this->request->request('id');
        $semester = $this->model->get($id);

        $list = [];
        if ($semester) {
            $list = \app\common\model\Semester::getWeekList($semester->start_date, $semester->end_date);
        }
        $this->success('', null, $list);
    }
}
